package cn.yangliu.springbatch.job;

import cn.yangliu.springbatch.entity.Role;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;

/**
 * the type of springbatch
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2021-07-12
 */
@Component
public class RoleReader extends JpaPagingItemReader<Role> {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @PostConstruct
    public void postConstruct() throws Exception {
        //这里选择JPA方式读数据 一个简单的 native SQL
        String jpqlQuery = "FROM Role";
        JpaJpqlQueryProvider<Role> queryProvider = new JpaJpqlQueryProvider<>();
        queryProvider.setJpqlQuery(jpqlQuery);
        queryProvider.setEntityClass(Role.class);
        queryProvider.afterPropertiesSet();
        setEntityManagerFactory(entityManagerFactory);
        setPageSize(3);
        setTransacted(false);
        setQueryProvider(queryProvider);
        //所有ItemReader和ItemWriter实现都会在ExecutionContext提交之前将其当前状态存储在其中,如果不希望这样做,可以设置setSaveState(false)
        setSaveState(true);
    }

    @Override
    public Role read() throws Exception {
        return super.read();
    }


    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
        Object userList = stepExecution.getJobExecution().getExecutionContext().get("userList");
        System.out.println("role reader : " + userList);
    }
}
